
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ColorConvertOp;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
 *
 * @author Madhu
 */
public class VideoFrame {

    final int FRAME_HEIGHT = 20;
    final int FRAME_WIDTH = 20;
    BufferedImage mainFrame;
    BufferedImage[] groups;
    private int pixelHeight;
    private int pixelWidth;
 //  private JLabel[] labels;
 //    private JFrame[] frames;

    public VideoFrame(File frame) throws IOException {
        mainFrame = convertToGrayscale(ImageIO.read(frame));
        this.updateDimensions();
        this.splitFrame();
    }

    private void updateDimensions() {
        pixelHeight = mainFrame.getHeight();
        pixelWidth = mainFrame.getWidth();
    }

    public int getHeight() {
        return pixelHeight;
    }

    public int getWidth() {
        return pixelWidth;
    }

    private void splitFrame() {
        int heightExcess = pixelHeight % FRAME_HEIGHT;
        int widthExcess = pixelWidth % FRAME_WIDTH;
        mainFrame = mainFrame.getSubimage(0, 0,
                pixelWidth - widthExcess,
                pixelHeight - heightExcess);

        this.updateDimensions();
        groups = new BufferedImage[(pixelWidth * pixelHeight) / (FRAME_HEIGHT * FRAME_WIDTH)];

        for (int i = 0; i < (pixelHeight / FRAME_HEIGHT) - 5; i++) {
            for (int j = 0; j < (pixelWidth / FRAME_WIDTH) - 5; j++) {
                groups[i] = mainFrame.getSubimage(
                        (FRAME_WIDTH * j),
                        (FRAME_HEIGHT * i),
                        (FRAME_WIDTH),
                        (FRAME_HEIGHT));
            }
        }
    }

    public BufferedImage[] getSplitFrames() {
        return groups;
    }

    public static BufferedImage convertToGrayscale(BufferedImage source) {
        BufferedImageOp op = new ColorConvertOp(
                ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
        return op.filter(source, null);
    }

  /*    public void displaySplitFrames() {
    frames = new JFrame[groups.length];
    labels = new JLabel[groups.length];
    for (int i = 0; i < groups.length; i++) {
    frames[i] = new JFrame();
    labels[i] = new JLabel(new ImageIcon(groups[i]));
    frames[i].add(labels[i]);
    frames[i].setVisible(true);
    }
    } */
}
